安装

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

安装过程中:

  1. 系统可能会提示你安装 Xcode 命令行工具(如果尚未安装)
  2. 会要求你输入管理员密码
  3. 最后会显示安装成功的消息

配置环境变量
安装完成后,Homebrew 会提示你将它的路径添加到你的 shell 配置文件中。对于 zsh(macOS Catalina 及更高版本的默认 shell),运行:

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc
source ~/.zshrc

验证安装
运行以下命令检查 Homebrew 是否安装成功:

brew --version

基本使用命令

常见问题解决

1 权限问题
如果遇到权限错误,可以尝试:

sudo chown -R $(whoami) /opt/homebrew

2 安装慢/卡住:可能是网络问题,可以尝试:

which brew

如果没有任何输出,说明 Homebrew 未安装。
(2) 安装 Homebrew
如果未安装,可以通过以下命令安装 Homebrew(适用于 macOS 或 Linux):

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

(3) 配置 Homebrew 到 PATH
安装完成后,Homebrew 通常会提示你将它的路径添加到你的 shell 配置文件中(如 ~/.zshrc 或 ~/.bash_profile)。如果没有自动添加,可以手动添加以下内容到 ~/.zshrc 文件:

echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zshrc

然后重新加载配置文件:

source ~/.zshrc

(4) 验证安装
运行以下命令验证 Homebrew 是否安装成功:

brew --version

如果显示 Homebrew 的版本号,说明安装成功。

为 Homebrew 配置国内镜像源的完整指南

由于网络原因,直接从官方源安装可能较慢,以下是配置国内镜像源的方法:
1. 中科大镜像源配置(推荐)
替换 Homebrew 核心仓库

# 替换 brew.git 
git -C "$(brew --repo)" remote set-url origin https://mirrors.ustc.edu.cn/brew.git 
# 替换 homebrew-core.git 
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-core.git 
# 替换 homebrew-cask.git(用于GUI应用) 
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.ustc.edu.cn/homebrew-cask.git

替换 Homebrew Bottles(预编译二进制包)
对于 zsh 用户:

echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles' >> ~/.zshrc source ~/.zshrc

2. 清华镜像源配置(备选)
替换仓库源

# 替换 brew.git 
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git 
# 替换 homebrew-core.git 
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git 
# 替换 homebrew-cask.git 
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git

替换 Bottles 源

echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.zshrc source ~/.zshrc

3. 验证配置
检查是否配置成功:

brew config | grep 'HOMEBREW_BOTTLE_DOMAIN'

4. 重置为官方源(如需还原)

# 重置 brew.git 
git -C "$(brew --repo)" remote set-url origin https://github.com/Homebrew/brew.git 
# 重置 homebrew-core.git 
git -C "$(brew --repo homebrew/core)" remote set-url origin https://github.com/Homebrew/homebrew-core.git 
# 重置 homebrew-cask.git 
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://github.com/Homebrew/homebrew-cask.git 
# 删除环境变量 
sed -i '' '/HOMEBREW_BOTTLE_DOMAIN/d' ~/.zshrc source ~/.zshrc

注意事项

  1. 只需选择一种镜像源(中科大或清华),不要同时配置多个
  2. 配置完成后,建议运行 brew update 更新索引
  3. 如果遇到问题,可以先尝试 brew doctor 诊断
  4. 某些特别新的软件包可能在镜像源中尚未同步,此时可以临时取消镜像设置